/* eslint-disable no-restricted-globals */
import React, { useEffect, useState } from 'react';
import classNames from 'classnames/bind';
import DoubleInput from './components/DoubleInput';
import ReqJson from './components/ReqJson';
import setting from './setting';
import styled from './index.less';
import CarList from './components/CarList';
import defaultIcon from './images/notif-icon.png';

const classes = classNames.bind(styled);
let timer = 0;
const Notify = ({ config, width, height, events, bigScreen, id, editable, settingData, data }) => {
  const [realTimeInfo, setRealTimeInfo] = useState({});
  const [notifyData, setNotifyData] = useState([]);
  const [realTimePreview, setRealTimePreview] = useState(false);
  const [notifyCenterPreview, setNotifyCenterPreview] = useState(false);

  // 更新store中的dataPoll
  const comSetDataPool = (dataPoll) => {
    const { setDataPool } = bigScreen;
    const { click } = events;
    setDataPool(click, dataPoll);
  };

  // 获取通知图标
  const getIconUrl = () => {
    const {
      universal: { notifIcon },
    } = config;
    const { type, iconUrl } = notifIcon;
    return type === 0 || !iconUrl ? defaultIcon : iconUrl;
  };

  // 实时消息通知
  const realTimeStyle = (type) => {
    const { realTime } = config;
    const { size, position, notifBgColor, notifBorderColor, notifBorderSize, notifRadius, notifTitle, notifContent, bgBlur } = realTime;

    const [w, h] = size.split(',');
    const [x, y] = position.split(',');
    if (type === 'card') {
      return {
        bBorder: `${notifBorderSize}px ${notifBorderColor} solid`,
        aBorder: `${notifBorderSize}px ${notifBorderColor} solid`,
        borderRadius: `${notifRadius}px`,
        width: `${w}px`,
        height: `${h}px`,
      };
    }
    if (type === 'font') {
      return {
        notifTitle,
        notifContent,
      };
    }
    return {
      backdropFilter: `blur(${bgBlur}px)`,
      borderRadius: `${notifRadius}px`,
      backgroundColor: notifBgColor,
      width: `${w}px`,
      height: `${h}px`,
      left: `${x}px`,
      top: `${y}px`,
    };
  };

  // 消息中心样式
  const notifyCenterStyle = (type) => {
    const { notifyCenter } = config;
    const { size, position, notifBgColor, defaultConfig, activeConfig, notifySpacing, bgBlur } = notifyCenter;
    const [w, h] = size.split(',');
    const [x, y] = position.split(',');
    if (type === 'default') {
      return defaultConfig;
    }
    if (type === 'card') {
      const { realTime } = config;
      const carH = realTime.size.split(',')[1] || 0;
      const { notifBorderColor, notifBorderSize, notifRadius } = defaultConfig;
      const { notifBorderColor: aBorderColor, notifBorderSize: aBorderSize, notifBgColor: aColor } = activeConfig;
      return {
        bBorder: `${notifBorderSize}px ${notifBorderColor} solid`,
        aBorder: `${aBorderSize}px ${aBorderColor} solid`,
        aColor,
        borderRadius: `${notifRadius}px`,
        width: `${w - 16}px`,
        height: `${carH}px`,
      };
    }
    if (type === 'font') {
      const { notifTitle, notifContent } = defaultConfig;
      return {
        notifTitle,
        notifContent,
      };
    }
    if (type === 'space') {
      return {
        margin: `${notifySpacing}px 0px`,
        padding: '0px 5px',
        display: 'flex',
        justifyContent: 'center',
      };
    }
    return {
      backdropFilter: `blur(${bgBlur}px)`,
      backgroundColor: notifBgColor,
      width: `${w}px`,
      height: `${h}px`,
      left: `${x}px`,
      top: `${y}px`,
    };
  };

  // 处理实时消息
  const handleRealTime = (info) => {
    timer && clearTimeout(timer);
    const findRealTime = info.find((f) => !f.status);
    if (findRealTime) {
      setRealTimeInfo(findRealTime);
      if (!editable) {
        notifyCenterPreview || setRealTimePreview(true);
        timer = setTimeout(() => {
          timer && clearTimeout(timer);
          setRealTimePreview(false);
          timer = setTimeout(() => {
            handleRealTime(info);
          }, 1000);
        }, config.realTime.autoClose * 1000);
      }
    } else {
      setRealTimePreview(false);
      setRealTimeInfo({});
    }
  };

  // 标记已读
  const maskHaveRead = (idV) => {
    if (notifyData.length !== 0) {
      const eacheData = () => {
        let otherId = '';
        const newData = notifyData.map((m) => {
          if (m.id === idV) {
            m.status = 1;
            if (m.otherId) {
              // eslint-disable-next-line prefer-destructuring
              otherId = m.otherId;
            }
          }
          return m;
        });
        handleRealTime(newData);
        comSetDataPool({ id: idV, otherId });
      };

      if (settingData.mode === 1) {
        eacheData();
      } else {
        const { axiosRequest } = bigScreen;
        const {
          universal: { markConfig },
        } = config;
        if (markConfig) {
          const { url, methed, body, headers = {} } = JSON.parse(markConfig.replaceAll(':id', idV));
          const upperCaseMethed = methed.toUpperCase();
          let result = null;
          if (upperCaseMethed === 'GET') {
            result = axiosRequest(
              {
                method: upperCaseMethed,
                url,
              },
              headers
            );
          } else {
            result = axiosRequest(
              {
                method: upperCaseMethed,
                url,
                body,
              },
              headers
            );
          }
          result.then((info) => {
            if (!info.error) {
              eacheData();
            }
          });
        }
      }
    }
  };

  // 页面初始化
  useEffect(() => {
    // 初始化变量
    comSetDataPool({ id: '', otherId: '' });
    // 实时消息
    const rtDiv = document.getElementById(`real_time_${id}`);
    if (rtDiv) {
      const canvasContainer = document.querySelector('.uc-flow-panel');
      canvasContainer && canvasContainer.appendChild(rtDiv);
    }
    // 消息中心
    const ncDiv = document.getElementById(`notify_center_${id}`);
    if (ncDiv) {
      const canvasContainer = document.querySelector('.uc-flow-panel');
      canvasContainer && canvasContainer.appendChild(ncDiv);
    }
    return () => {
      const realTimeDiv = document.getElementById(`real_time_${id}`);
      realTimeDiv && realTimeDiv.remove();
      const notifyCenterDiv = document.getElementById(`notify_center_${id}`);
      notifyCenterDiv && notifyCenterDiv.remove();
    };
  }, []);

  // 数据发生变化时，同步到状态中
  useEffect(() => {
    if (data && data.length !== 0) {
      const {
        notifyCenter: { maxCount },
      } = config;
      if (data.length > maxCount) {
        data.length = maxCount;
      }
      handleRealTime(data);
      setNotifyData(data);
    }
    return () => {
      timer && clearTimeout(timer);
    };
  }, [JSON.stringify(data), config.notifyCenter.maxCount]);

  // 预览实时消息
  useEffect(() => {
    if (editable) {
      setRealTimePreview(config.realTime.isPriview);
    } else {
      setRealTimePreview(false);
    }
  }, [config.realTime.isPriview]);

  // 预览消息中心
  useEffect(() => {
    if (editable) {
      setNotifyCenterPreview(config.notifyCenter.isPriview);
    } else {
      setNotifyCenterPreview(false);
    }
  }, [config.notifyCenter.isPriview]);

  const dStyle = notifyCenterStyle('default');
  return (
    <div className={styled['notif-box']}>
      <img
        style={{ width, height, cursor: 'pointer' }}
        src={getIconUrl()}
        alt="消息通知"
        onClick={() => {
          setRealTimePreview(false);
          setNotifyCenterPreview(!notifyCenterPreview);
        }}
      />
      <div
        id={`real_time_${id}`}
        style={realTimeStyle()}
        className={classes('notify-window-box', realTimePreview ? 'notify-window-box-show' : '')}
        onClick={() => {
          maskHaveRead(realTimeInfo.id);
        }}
      >
        <CarList {...realTimeInfo} cardStyle={realTimeStyle('card')} font={realTimeStyle('font')}></CarList>
      </div>
      <div id={`notify_center_${id}`} style={notifyCenterStyle()} className={classes('notify-window-box', notifyCenterPreview ? 'notify-window-box-show' : '')}>
        <div className={styled['result-content']}>
          <div
            className={styled['result-title']}
            style={{
              ...dStyle.notifTitle,
              borderColor: dStyle.notifTitle.color,
            }}
          >
            <div>消息中心</div>
          </div>
          <div className={styled['result-body']}>
            {notifyData.map((m) => (
              <div
                style={notifyCenterStyle('space')}
                onClick={() => {
                  maskHaveRead(m.id);
                }}
              >
                <CarList {...m} cardStyle={notifyCenterStyle('card')} font={notifyCenterStyle('font')}></CarList>
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

Notify.setting = setting;
Notify.styleConfig = {
  doubleInput: (props) => <DoubleInput {...props} />,
  reqJson: (props) => <ReqJson {...props} />,
};
export default Notify;
